﻿<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>客户管理</title>
    <script src="~/lib/vue/vue.global.min.js"></script>
    <script src="~/lib/element-plus/index.full.js"></script>
    <link href="~/lib/element-plus/index.min.css" rel="stylesheet" />
    <link href="~/lib/element-plus/index.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

    <style>
        #sidebar {
            width: 220px !important;
            min-width: 220px !important;
            max-width: 220px !important;
            flex-shrink: 0 !important;
        }

        .container {
            width: 95%;
            height: 600px;
            margin: 20px auto;
            border: 1px solid #ebeef5;
            border-radius: 4px;
            padding: 20px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        /* 表格表头样式（新增） */
        .el-table__header th {
            background-color: #F5F5F5 !important; /* 表头背景色，可自定义 */
            color: #191919 !important; /* 表头文字颜色，可自定义 */
        }
        .search-area {
            margin-bottom: 16px;
        }

        .btn-group {
            margin-bottom: 16px;
        }

        .custom-select,
        .el-input {
            width: 150px !important;
        }

        .el-table__fixed-column .cell {
            white-space: nowrap !important;
            overflow: hidden !important;
            text-overflow: ellipsis !important;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- 搜索区域 -->
        <div class="search-area">
            <el-form inline>
                <el-form-item label="客户">
                    <el-input v-model="Form.customerQuery" placeholder="请输入客户名称/编号">

                    </el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="Form.status" placeholder="请选择" class="custom-select">
                        <!-- 循环状态字典选项：label 显示文字，value 绑定实际值（1/2） -->
                        <el-option v-for="item in statusOptions"
                            :key="item.dictValue"  
                            :label="item.dictLabel" 
                            :value="item.dictValue"> <!-- 选中后的值是 1 或 2 -->
                         </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属行业">
        
                    <!-- v-model 绑定表单中“所属行业”的选中值 -->
                    <el-select v-model="Form.job_type" class="custom-select" placeholder="请选择">
                        <el-option v-for="item in industryOptions"
                                   :key="item.value"
                                   :label="item.dictLabel"
                                   :value="item.dictValue"></el-option>
                    </el-select>

                </el-form-item>
                <el-form-item label="联系人">
                    <el-input placeholder="请输入" v-model="Form.contact_person">
                    </el-input>

                </el-form-item>
                <el-form-item>
                    <el-button v-on:click="resetSearch2">重置</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click ="loadData">查询</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 功能按钮区域 -->
        <div class="btn-group">
            <el-button type="primary" v-on:click="goToAddPage">新增</el-button>
            <el-button>删除</el-button>
            <el-button>导出</el-button>
            <el-button>导入</el-button>
            <el-button>刷新</el-button>
        </div>

        <!-- 数据表格区域 -->
        <el-table :data="tableData" border style="width: 100%">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="customer_code" label="客户编码" fixed="left" width="150">
                <template #default="scope">
                    <!-- 点击客户编号触发跳转 -->
                    <span style="color: #409EFF; cursor: pointer;"
                    v-on:click ="gotoDetail(scope.row.customer_code)">
                        {{ scope.row.customer_code }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="customer_name" label="客户名称" fixed="left" width="120"></el-table-column>
            <el-table-column prop="industry_name" label="所属行业" width="120"></el-table-column>
            <el-table-column prop="customer_source_name" label="客户来源" width="120"></el-table-column>
            <el-table-column prop="contact_person" label="联系人" width="120"></el-table-column>
            <el-table-column prop="contact_phone_number" label="联系电话" width="120"></el-table-column>
            <el-table-column prop="email_address" label="电子邮箱" width="120"></el-table-column>
            <el-table-column prop="sales_dept_name" label="销售部门" width="120"></el-table-column>
            <el-table-column prop="sales_person_name" label="销售负责人" width="130"></el-table-column>
            <el-table-column prop="status" label="状态" width="90">
                <template #default="scope">
                    <!-- 先将 status 转换为数字再判断 -->
                    {{ Number(scope.row.status) === 1 ? '启用' : Number(scope.row.status) === 2 ? '停用' : '未知状态' }}
                </template>
            </el-table-column>
            <el-table-column prop="customers_address" label="客户地址" width="120"></el-table-column>
            <el-table-column prop="account_name" label="账号名称" width="120"></el-table-column>
            <el-table-column prop="taxid" label="纳税人识别号" width="150"></el-table-column>
            <el-table-column prop="bank_account" label="银行账号" width="120"></el-table-column>
            <el-table-column prop="opening_bank" label="开户银行" width="120"></el-table-column>
            <el-table-column prop="bkaddr" label="开户银行地址" width="150"></el-table-column>
            <el-table-column prop="create_by" label="操作人" width="120"></el-table-column>
            <el-table-column prop="create_time" label="操作时间" width="120"></el-table-column>
            <el-table-column label="操作" fixed="right">
                <template #default="scope">
                    <el-button-group>
                        <!-- 编辑按钮：点击时携带客户编号跳转至编辑页 -->
                        <el-button type="text"
                                   v-on:click="goToEdit(scope.row.customer_code)">
                            编辑
                        </el-button>
                        <el-button type="text" style="color: red;" v-on:click="handleDelete(scope.row.customer_code)">删除</el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination v-on:size-change="handleSizeChange"
                       v-on:current-change="handleCurrentChange"
                       :current-page="pageIndex"
                       :page-sizes="[1,2, 3, 4]"
                       :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="totalCount"
                       style="margin-top: 16px;">
        </el-pagination>

    </div>

    <script>
        const { createApp, onMounted, reactive, ref } = Vue;
        const app = createApp({
            setup() {
                const tableData = ref([]); // 表格数据
                const totalCount = ref(0); // 总记录数
                const pageIndex = ref(1);  // 当前页码
                const pageSize = ref(2);   // 每页条数


                // 2. 搜索表单数据、
                const Form = reactive({
                    customerQuery: '',      // 客户名称/编号（模糊查询）
                    status: '',
                    job_type: '',
                    contact_person: '',     // 联系人（模糊查询）
                });

               const industryOptions = ref([]); // 所属行业的字典选项

               //获取状态数据从数据字典来
                const statusOptions = ref([]);

                // 获取状态字典数据（从后端接口）
                const getStatusDict = async () => {
                    try {
                        // 假设状态字典的类型编码是 "EnableDisable"（需与后端字典表一致）
                        const response = await axios.get('/api/Dict/datas/EnableDisable');
                        statusOptions.value = response.data; // 存储接口返回的字典数据
                    } catch (error) {
                        console.error('获取状态字典失败：', error);
                        ElementPlus.ElMessage.error('获取状态数据失败，请稍后再试');
                    }
                };


                 // 4. 获取“所属行业”字典数据
                const getIndustryDict = async () => {
                    try {
                        const response = await axios.get('/api/Dict/datas/Industry');
                      industryOptions.value = response.data;
                    } catch (error) {
                        console.error('获取所属行业字典失败：', error);
                        ElementPlus.ElMessage.error('获取所属行业数据失败，请稍后再试');
                    }
                };

                // 加载分页数据（使用 axios）
        const loadData = async () => {
            try {
                // 1. 准备请求参数（包含当前页码和页大小）
                const requestParams = {
                    currentPage: pageIndex.value, // 对应后端参数 currentPage
                    pageSize: pageSize.value,     // 对应后端参数 pageSize
                    // 客户编号/名称：前端输入框统一输入，后端拆分处理
                customer_code: Form.customerQuery || null,  // 优先作为编号查询
                customer_name: Form.customerQuery || null,    //同时作为名称模糊查询
                status: Form.status ? Number(Form.status) : null,  // 转换为数字
                job_type: Form.job_type ? Number(Form.job_type) : null,  // 转换为数字
                contact_person: Form.contact_person || null,  // 联系人模糊查询
                };

                // 2. 发送 GET 请求，通过 params 传递参数（关键修复）
                const response = await axios.get("/CustomerManagement/GetCustomerPage2", {
                    params: requestParams  // 注意：参数必须放在 params 中
                });

                // 3. 赋值数据（保持不变）
                tableData.value = response.data.data || [];
                totalCount.value = response.data.total || 0;
                console.log('分页数据',response.data.data)
                console.log('总条数',response.data.total)


            } catch (error) {
                console.error("加载数据失败：", error);
                ElementPlus.ElMessage.error("数据加载失败，请重试");
            }
        };

                // 分页事件：每页条数变化
                const handleSizeChange = (newSize) => {
                    pageSize.value = newSize;
                    loadData(); // 重新加载数据
                };

                // 分页事件：当前页变化
                const handleCurrentChange = (newPage) => {
                    pageIndex.value = newPage;
                    loadData(); // 重新加载数据
                };

                // 重置搜索条件（修复未定义的 searchParams）
                const resetSearch = () => {
                    // 若需要搜索功能，先定义 searchParams
                    // const searchParams = reactive({ customerName: "" });
                    pageIndex.value = 1;
                    loadData();
                };

                // 页面加载时初始化数据
                onMounted(() => {
                    loadData();
                    getIndustryDict();
                    getStatusDict();
                });


                             // 重置搜索条件
                const resetSearch2 = () => {
                    // 清空表单
                    Form.customerQuery = '';
                    Form.status = '';
                    Form.job_type = '';
                    Form.contact_person = '';
                    // 重置页码并重新加载
                    pageIndex.value = 1;
                    loadData();
                };


                   // 跳转详情页方法：通过URL参数传递customerCode
                const gotoDetail = (customerCode) => {
                  // 构造详情页URL，参数为customerCode
                  window.location.href = `/CustomerManagement/Detail?customerCode=${customerCode}`;
                };


                 const goToEdit = (customerCode) => {
                  // 跳转到编辑页，并通过URL参数传递客户编号
                  window.location.href = `/CustomerManagement/Edit?customerCode=${customerCode}`;
                };

                // 跳转到新增页面
                const goToAddPage = () => {
                    window.location.href = '/CustomerManagement/Add';
                };



        // 处理删除操作：弹窗确认 + 调用后端接口
        const handleDelete = (customerCode) => {
          ElementPlus.ElMessageBox.confirm(
            '此操作将逻辑删除该客户，是否继续？',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(async () => {
            try {
              // 调用后端删除接口（逻辑删除，更新is_delete字段）
              const res = await axios.put('/CustomerManagement/DeleteCustomer', {
                     CustomerCode: customerCode,  
                     IsDelete: "1"                
              });
              if (res.data.success) {
                ElementPlus.ElMessage.success('删除成功');
                loadData(); // 重新加载表格数据
              } else {
                ElementPlus.ElMessage.error(res.data.Message || '删除失败');
              }
            } catch (err) {
              console.error('删除失败:', err);
              ElementPlus.ElMessage.error(err.response?.data?.Message || '服务器异常');
            }
          }).catch(() => {
            ElementPlus.ElMessage.info('已取消删除');
          });
        };


                return {
                    tableData,
                    totalCount,
                    pageIndex,
                    pageSize,
                    loadData,
                    handleSizeChange,
                    handleCurrentChange,
                    resetSearch,
                    goToAddPage,
                    Form,
                    industryOptions,
                    statusOptions,
                    resetSearch2,
                    gotoDetail,
                    goToEdit,
                    handleDelete,

                };

            }
        });
        app.use(ElementPlus);
        app.mount('.container');
    </script>
</body>

</html>